package com.yangzhe.algorithm.c038;

import java.util.ArrayList;
import java.util.List;

// 没有重复项数字的全排列
// 测试链接 : https://leetcode.cn/problems/permutations/
public class Code03_Permutations {

    /**
     * 思路：递归
     * 1. i位置和 +0 +1 ... +<length位置的数交换，继续第2步递归，完成后交换回来
     * 2. 递归i+1，i+2....i+<length的位置
     * 3. 直到i=length收集一次答案
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        f(nums, 0, result);

        return result;
    }

    public static void f(int[] nums, int i, List<List<Integer>> result) {
        if (i == nums.length) {
            List<Integer> list = new ArrayList<>();
            for (int j = 0; j < nums.length; j++) {
                int num = nums[j];
                list.add(num);
            }

            result.add(list);
        } else {
            for (int j = i; j < nums.length; j++) {
                swap(nums, i, j);
                // 继续递归i + 1位置
                f(nums, i + 1, result);
                // 恢复数组状态
                swap(nums, i, j);
            }
        }
    }

    public static void swap(int[] nums, int x, int y) {
        int temp = nums[x];
        nums[x] = nums[y];
        nums[y] = temp;
    }


    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> ans = permute(nums);
        for (List<Integer> list : ans) {
            for (int num : list) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }

}
